package TuiLayer;
import java.util.Scanner;
import ControlLayer.*;
/**TuiLayer package sets the location for LoanUI class.
 * 
 * Scanner package is used here, because it provides tracking on the inputs from a
 * keyboard. This gives user(Private Person) the ability to have control on
 * LoanUI. The control is exercised by inserting different values through the
 * keyboard. This means that AddressBookUI behaves strictly in accordance to the user
 * preferences.
 * 
 * The ControlLayer package is imported, because TUIs must be able to access classes
 * in the ControlLayer - AddressController, RegisterController and LoanController.
 * ---------------------------------------------------------------------------------
 * AddressBookUI class is devided in _ sections. In each section(except the first
 * one) methods with similar functionalities are placed.
 * 
 * Section Contents:
 *  Variables
 *  Constructors
 *      - LoanUI()
 *      - start()
 *  UserTrackers
 *      - dvdLoan()
 *      - writeLoanMenu()
 *  Methods
 *      - loanDvd()
 *      - returnDvd()
 *      - printLoans()
 *      - editLoan()
 *  Inputs
 *      - inputContinue()
 *      - inputId()
 *      - inputSerialNumber()
 *      - inputDate()
 *      - inputPeriod()
 *      - inputPersonName()
 *      - inputPersonID()
 *      - inputDvdTitle()
 *      - inputPeriodLoaned()
 *  Printers
 *      - writeError()
 */

public class LoanUI
{
  /** VARIABLES */    
    //LoanUI has to send the user preferences as commands to LoanController. For
    //the purpose to provide access to the controller the following object
    //reference(association) is needed.
    private LoanController tellCtr; //Reference to LoanController.
    
  /** CONSTRUCTORS */
  public LoanUI()
  //Ceates an instance of LoanUI class.
  {
      tellCtr = new LoanController();
      //This initializes a new LoanController.
  }
  
  public void start()
  //Launches the UI and initializes the optionChoice functionality. User is
  //now able to use the DVDUI.
  {
      dvdLoan();    //See User Tracker section.
  }
  
  /** USER TRACKERS */
  public void dvdLoan()
  //Provides the optionChoice functionality.
  {
      boolean isRunning = true;
      //This indicates whether the LoanUI is launched and running.
      
      while(isRunning)
      //This can be interpreted like this: 'While the application is running perform
      //the following tasks below'. If the boolean expression isRunning becomes
      //false, then the interface stops working and the application is closed. User
      //cannot use the LoanUI anymore and goes back to MainMenu interface.
      {
          int optionChoice = writeLoanMenu();
          //Before determing what the UI have to execute, it will acquire user
          //optionChoice first, by calling this method.
          
          if(optionChoice == 1)
          //User inputs 1 as an optionChoice - UI prompts user for loan details. The
          //DVD is loaned.
          {
              loanDvd();
          }
          
          else if(optionChoice == 2)
          //User inputs 2 as an optionChoice - UI displays a list of all loans.
          {
              printLoans();
          }
          
          else if(optionChoice == 3)
          //User inputs 3 as an optionChoice - UI update a loan chosen by user.
          {
              editLoan();
          }
          
          else if(optionChoice == 4)
          //User inputs 4 as an optionChoice - UI deletes a loan chosen by user. The
          //DVD is returned.
          {
              returnDvd();
          }
          
          else if(optionChoice == 0)
          //User inputs 0 as an optionChoice -  User is redirected back to the
          //MainMenuUI.  
          {
              isRunning = false; //Variable isRunning becomes false. UI shuts down.
          }
          
          else if(optionChoice != 1 && optionChoice != 2 && optionChoice != 3
                  && optionChoice != 4 && optionChoice !=0)
          //This checks whether the optionChoice number is a valid command. User 
          //makes invalid input(the number is not within the range from 0 to 4).
          //A message is displayed to notify about the problem.                
          {
              writeError();
              inputContinue();
          }
      } 
  } 
   
  private int writeLoanMenu()
  //Acquires optionChoice. It creates a keyboard object(of Scanner class), so 
  //that user can input her optionChoice. It is important to note that this
  //method also visualizes the UI.
  {
      Scanner keyboard = new Scanner(System.in);
      //Creates the keyboard object.
            
      System.out.println("\f *** Loan Menu ***"); 
      System.out.println(" (1) Set New Loan");
      System.out.println(" (2) List All Loans");
      System.out.println(" (3) Update Loan Details");
      System.out.println(" (4) Remove Loan");
      System.out.println(" (0) Return to Main Menu");
      System.out.print("\n Choose an option: ");
      //LoanUI visualization. It is made by printing these lines in the Terminal
      //window.
      
      String checkInput = keyboard.nextLine();
      //This tracks user inputs by calling Scanner nextLine() method on each input.
      
      int optionChoice; //Local variable, where user option choice will be stored.
      
      try
      //After getting user input, this try-catch structure checks whether the
      //input is a number(integer). This allows the use of integers, instead of 
      //strings for determing the user option choice and at the same time this
      //prevents system from crashing.
      {
          optionChoice = Integer.parseInt(checkInput);
          //If it is a number then UI gets an optionChoice to check whether it
          //there is such an option.
      }
      
      catch(NumberFormatException wrongInput)
      {
          optionChoice = -1;
          //If the input is not a number, then this code will make UI display a
          //message, to notify user about the problem.
      }
      
      return optionChoice; //Sends what is the user optionChoice.
  }
  
  /** METHODS */
  public void loanDvd()
  //Prompts user to add attributes for the Loan which is going to be
  //added(created) in the LoanRegister.
  {
      try
      {
          tellCtr.setLoanRegister(inputId(), inputDate(), inputPeriod(),
                                    inputDvdTitle() ,inputPersonID());
          //For each variable, UI prompts first for a value, then user has to
          //input it. After all attributes are done, person is added in the
          //AddressBook.
          inputContinue();
      }
      catch(Exception noPersonOrDVD)
      {
          System.out.println("You must choose a person and DVD that is already created in the system");
          //Displays an error message.
          inputContinue();
      } 
  }
    
  public void returnDvd()
  //Prompts user to add attribute for id and loan period. If the id is valid
  //then a loan with such attributes will be removed from the LoanRegister.
  {
      try
      {
          System.out.println(tellCtr.returnLoan(inputId(), inputPeriodLoaned()));
          inputContinue();
      }
      catch(Exception notFound)
      {
          System.out.println("You must choose a valid ID of loan");
          //Displays an error message.
          inputContinue();
      }
  }
    
  public void printLoans()
  //Displays a list of all loans in the LoanRegister.
  {
      System.out.println(tellCtr.printLoans());
      inputContinue();
      //Prompts user to press Enter to continue using the UI.
  }
    
  public void editLoan()
  //Prompts user to add attribute for id. If the id is valid then user 
  //will be allowed to change attributes of a loan with such an id.
  {
      try
      {
          System.out.println("Input the loan's ID that you want to change");
          tellCtr.editLoan(inputId(), inputDate(), inputPeriod());
          inputContinue();
      }
      catch(Exception notFound)
      {
          System.out.println("Loan doesn't exist");
          //Displays an error message if there is no loan with such an id.
          inputContinue();
          //Prompts user to press Enter to continue using the UI.
      }
  }
    
  /** INPUTS*/
  public void inputContinue()
  //Prompts user to press Enter to continue using the UI.
  {
      Scanner keyboard = new Scanner(System.in);  
      System.out.println(" Press Enter to continue:  ");
      String code = keyboard.nextLine();
  }
               
  public int inputId()
  //Prompts user to define a value for PersonID.
  {
      boolean ok = false;
      //This boolean controls the while loop, which is waiting for the user input.
      //When it becomes true, while stops.
      int id = 0;
      
      while(!ok)
      {
          Scanner keyboard = new Scanner(System.in);
          System.out.println(" Write Id:  ");
          
          try
          {
              id = keyboard.nextInt();
              ok = true;
          }
          catch (Exception notInteger)
          {
              System.out.println("You should insert a number");
              String input = keyboard.nextLine();
          }
      }
      return id;
  }
  
  public String inputSerialNumber()
  //Prompts user to define a value for serialNumber.
  {
      Scanner keyboard = new Scanner(System.in);
      System.out.println(" Write Serialnumber:  ");
      String code = keyboard.nextLine();
      return code;           
  }

  public String inputDate()
  //Prompts user to define a value for date.
  {
      Scanner keyboard = new Scanner(System.in);  
      System.out.println("Type Loan Date:  ");
      String code = keyboard.nextLine();
      return code;
  } 
  
  public int inputPeriod()
  //Prompts user to define a value for period.
  {
      boolean ok = false;
      int id = 0;
      while(!ok)
      {
          Scanner keyboard = new Scanner(System.in);
          System.out.println(" Write how many days you loan the dvd: ");
          try
          {
              id = keyboard.nextInt();
              ok = true;
          }
          catch (Exception notInteger)
          {
              System.out.println("Write a number.");
              String input = keyboard.nextLine();
          }
      }
      return id;
  }
  
  public String inputPersonName()
  //Prompts user to define a value for personName.
  {
      Scanner keyboard = new Scanner(System.in);  
      System.out.println("Type in name of Loaner: ");
      String code = keyboard.nextLine();
      return code;
  }
    
  public String inputPersonID()
  //Prompts user to define a value for personID.
  {
      Scanner keyboard = new Scanner(System.in);  
      System.out.println("Type in ID of Loaner: ");
      String code = keyboard.nextLine();
      return code;
  }
    
  public String inputDvdTitle()
  //Prompts user to define a value for dvdTitle.
  {
      Scanner keyboard = new Scanner(System.in);  
      System.out.println("Type title of DVD you want to loan:  ");
      String code = keyboard.nextLine();
      return code;
  }
    
  public int inputPeriodLoaned()
  //Prompts user to define a value for periodLoan.
  {
      int code=0;
      Scanner keyboard = new Scanner(System.in);  
      System.out.println("Type after how many days you returned it:  ");
      
      try
      {
          code = keyboard.nextInt();
      }
      catch (Exception notInteger)
      {
          System.out.println("Write a number.");
          String input = keyboard.nextLine();
      }
        
      return code;
  }
  
  /** PRINTERS */
  public void writeError()
  //Prints an error message in the terminal window.
  {
      System.out.println("\n [ERROR]:\n You can only insert\n numbers 1, 2, 3 , 4"
                                + " and\n 0 for an option choice."
                                + "\n\n");
      inputContinue();
  }
}